import {Image, InfiniteScroll, List} from 'antd-mobile'
// mock数据
import {fetchListApi} from '@/api/ChannelList.ts'
import type {ListRes} from '@/api/ChannelList.ts'
import {useEffect, useState} from "react";
import {useNavigate} from "react-router-dom";

type Props = {
    channelId: string
}
const HomeList = (props: Props) => {
    const {channelId} = props
    const [page, setPage] = useState(1)

    const [list, setList] = useState<ListRes>({
        page: 1,
        per_page: 10,
        results: [],
        total_count: 16
    })
    useEffect(() => {
        const getList = async () => {
            try {
                const res = await fetchListApi({
                    channel_id: channelId,
                    page: 1
                })
                setList(res.data.data)
            } catch (error) {
                // @ts-ignore
                throw new Error("获取数据失败", error)
            }
        }
        getList()
    }, [channelId]);

    // 开关 标记是否还有新数据
    // 上拉加载的必要条件 1. hasMore必须为true 2. 必须小于threshold阈值
    const [hasMore, setHasMore] = useState(true)
    // 请求加载数据函数 异步
    const loadMore = async () => {
        // 编写下一步核心逻辑

        try {
            const res = await fetchListApi({
                channel_id: channelId,
                page: page
            })
            setList({
                ...list,
                page: page,
                results: [...list.results, ...res.data.data.results]
            })

            if (res.data.data.results.length === 0) {
                setHasMore(false)
            } else {
                setPage(page + 1)
            }
        } catch (error) {
            // @ts-ignore
            throw new Error("获取数据失败", error)
        }

    }

    // 点击跳转详情页
    const navigate = useNavigate()
    const gotoDetail = (id: string) => {
        navigate(`/detail?id=${id}`)
    }

    return (
        <>
            <List>
                {list.results.map((item) => (
                    <List.Item
                        onClick={() => gotoDetail(item.id)}
                        key={item.id}
                        prefix={
                            <Image
                                src={item.cover.images[0] ? item.cover.images[0] : '@/assets/react.svg'}
                                style={{borderRadius: "50%"}}
                                fit="cover"
                                width={50}
                                height={50}
                            />
                        }
                        description={item.pubdate}>
                        {item.title}
                    </List.Item>
                ))}
            </List>

            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10}/>
        </>
    )
}

export default HomeList